﻿using System;

using ApplicationBoilerplate.DataProvider;

using MongoDB.Driver;

namespace MVCBootstrap.MongoDB {

	public class Connection : IConnection {
		protected readonly MongoDatabase database;

		public Connection(String connectionString) {
			MongoUrl url = MongoUrl.Create(connectionString);
			String databaseName = url.DatabaseName;
			MongoClient client = new MongoClient(url);
			MongoServer server = client.GetServer();
			this.database = server.GetDatabase(databaseName);
		}

		public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class {
			return this.GetCollection<TEntity>();
		}

		public IMongoCollection<TEntity> GetCollection<TEntity>() where TEntity : class {
			return new Collection<TEntity>(this);
		}

		public MongoCollection<TEntity> Collection<TEntity>() where TEntity : class {
			return this.database.GetCollection<TEntity>(typeof(TEntity).Name.ToLower());
		}

		public void SaveChanges() {
            // Nothing happening here! Changes happens real-time!
            // No transactions!
		}

		public void Dispose() {
			// Nothing to do here!
		}
	}
}